<?
    require_once("config.php");

    class LineItem {
        var $id;
        var $title;
        var $type;
        var $dbid;
        private $options = array();
        
        function __construct($id,$title = '', $type = '', $options = array()) {
            $this->id = $id;
            $this->title = $title;
            $this->type = $type;
            $this->options = $options;
        }
        function AddOption($opt) { $this->options[] = $opt; }
        function Set($var,$val) {
            $this->$var = $val;
        }
        function GetQuery() {
            if ($this->dbid) {
                return "UPDATE listing_structure SET `important`='{$this->important}', `title`='{$this->title}', `type`='{$this->type}', `options`='" . implode(",",$this->options) . "' WHERE `id`='{$this->dbid}';";
            }
            else {
                $newlocation = DBM::FetchOne("SELECT MAX(location)+1 as location FROM listing_structure;");
                $query = "INSERT INTO listing_structure (title,type,options,location) VALUES ('{$this->title}','{$this->type}','" . implode(",",$this->options) . "',$newlocation);";
                return $query;
            }
        }
        function PerformUpdate() {
            $query = $this->GetQuery();
            DBM::Execute($query);
            if(strpos($query,"INSERT") !== false) {
                $this->dbid = DBM::LastInsertID();
            }
        }
        function Render() { 
            echo "<pre>
    Item ID     : {$this->id}
    Title       : {$this->title}
    Type        : {$this->type}
    DBID        : {$this->dbid}
    Options     : " . count($this->options) . "\n";
            $count = 0;
            foreach ($this->options as $option) {
                echo "        $count = $option\n";
                $count++;
            }
            echo "</pre>";
        }
    }   
    
    if ($_POST) {
        $all = array();
        
        foreach ($_POST as $key => $val) {
            $matches = array();
            if (preg_match("/(option_(\d+))_(\d+)/",$key,$matches)) {
                $itemid = $matches[2];
                $optionid = $matches[3];
                
                if (!$all[$itemid]) $all[$itemid] = new LineItem($itemid);
                $all[$itemid]->AddOption($val);
            }
            else if (preg_match("/([a-zA-Z]+)_(\d+)/",$key,$matches)) {
                $propertyname = $matches[1];
                $itemid = $matches[2];
                
                if (!$all[$itemid]) $all[$itemid] = new LineItem($itemid);
                $all[$itemid]->Set($propertyname,$val);
            }
        }
        
        foreach ($all as $id => $lineitem) {
            $lineitem->PerformUpdate();
        }
        
        // now delete any that should be deleted
        foreach (explode(",",$_POST['delete']) as $deleteid) {
            if ($deleteid) {
                $query = "DELETE FROM listing_structure WHERE id=$deleteid;";
                DBM::Execute($query);
            }
        }
        
        // and finally update the order
        $orderlist = explode(",",$_POST['order']);
        $orders = array();
        for ($x = 0; $x < count($orderlist); $x++) {
            $orders[$orderlist[$x]] = $x;
        }
        foreach ($all as $id => $lineitem) {
            if ($id) {
                $lineitem->Render();
                $query = "UPDATE listing_structure SET location = $orders[$id] WHERE id=" . $lineitem->dbid . ";";
                DBM::Execute($query);
            }
        }
        
        header("Location: admin_listingstructure.php");
    }
    else if ($_GET['action'] == "getitems") {
        $rows = DBM::FetchAllRows("SELECT * FROM listing_structure ORDER BY location ASC;");
        echo json_encode($rows);
    }
    else {
        $menu = new Menu("Other Actions");
        $menu->AddItem(new MenuItem("Reload Page",       "location.href=location.href",               AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Create a Listing",  "edit_listing.php",                          AuthConstants::ADMINISTRATORS));
        $menu->AddItem(new MenuItem("",                  "#",                                         AuthConstants::ADMINISTRATORS));
        $menu->AddItem(new MenuItem("Add Header",        "theform.AddLineItem(\"\",Types.HEADER)",   AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Add Checkbox(es)",  "theform.AddLineItem(\"\",Types.CHECKBOX)",  AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Add Radio Buttons", "theform.AddLineItem(\"\",Types.RADIO)",     AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Add Dropdown",      "theform.AddLineItem(\"\",Types.SELECT)",    AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Add Textarea",      "theform.AddLineItem(\"\",Types.TEXTAREA)",  AuthConstants::ADMINISTRATORS, true));
        $menu->AddItem(new MenuItem("Add Textfield",     "theform.AddLineItem(\"\",Types.TEXTFIELD)", AuthConstants::ADMINISTRATORS, true));
        
        MenuManager::AddMenu("Edit Listing Structure",$menu);
        
        Functions::PrintHeader("Edit Listing Structure");
        ?>
        <script type='text/javascript'>
            window.onload = function() { 
                theform = new EditableForm('items');
                
                // Add any items from the database:
                <?
                    $lineitems = DBM::FetchAllRows("SELECT * FROM listing_structure ORDER BY location ASC;");
                    foreach ($lineitems as $lineitem) {
                        echo "id = theform.AddLineItem('$lineitem[title]',Types." . strtoupper($lineitem['type']) . ",new Array(\"" . implode('","',explode(",",$lineitem['options'])) . "\"),$lineitem[important]);\n";
                        echo "theform.Bind(id,$lineitem[id]);\n";
                    }
                ?>
            }
            
            function update(thelist) {
                var outstr = Sortable.sequence(thelist);
                $("order").value = outstr;
            }

            function UpdateList() {
                Sortable.create('items',{
                    ghosting:false,
                    handle:'handle',
                    onUpdate:function(element) {
                        update('items');
                    }
                });
                update('items');
            }

        </script>
        
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        <!-- *****             This is the template for the line item               ***** -->
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        <div style='display:none;'>
            <li class='form_lineitem' id="itemtemplate">
                <div class='regularstuff'>
                    <div class='li_wrapper'>
                        <span class='imagespan'>
                            <img class='moveimg handle' src='<?=ThemeManager::GetImage("handle.png")?>' />
                            <img class='editimg edit_handle' src='<?=ThemeManager::GetImage("edit.png")?>' />
                            <img class='deleteimg delete_handle' src='<?=ThemeManager::GetImage("delete.png") ?>' />
                        </span>
                            <label><input type='checkbox' name='important' value='1' />Important</label>
                        <select name='type'>
                            <option value='header'>Header</option>
                            <option value='checkbox'>Checkboxes</option>
                            <option value='radio'>Radio Buttons</option>
                            <option value='select'>Select</option>
                            <option value='textarea'>Textarea</option>
                            <option value='textfield'>Textfield</option>
                        </select>
                    </div>
                    
                    <div class='title_type'>
                        <input type='text' name='title' class='hidden_input' />
                    </div>
                </div><br>
                <div class='hiddencontainer'><div class='options' style='display:none;' name='options'></div></div>
            </li>
        </div>
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        <!-- **************************************************************************** -->
        
        <?
            InfoMessage::Show("Types of Controls and 'Important' Items","<ul>
                <li>Use a <b>header</b> control when you want to separate different sections.</li>
                <li>Use a <b>checkbox</b> control when you want to show a list of items and allow multiple items to be selected</li>
                <li>Use a <b>radio button</b> control when you have only a few items and only want one selected</li>
                <li>Use a <b>dropwdown menu</b> control when you have a lot of items and only want one selected</li>
                <li>Use a <b>textfield</b> control to store a little text</li>
                <li>Use a <b>textarea</b> control to store a lot of text</li>
            </ul><br>Selecting an item as 'important' will show that line item in the search results.  If an item is not 'important' then it will only be displayed when the listing details are viewed.");
        ?>  
        
        
        
        
        
        
        <form method="POST" action="admin_listingstructure.php">
            <input type='hidden' name='itemcount' id='itemcount' value='0' />
            <input type='hidden' name='order' id='order' />
            <input type='hidden' name='delete' id='delete' />
            <ul class='editableform' id='items'>
            </ul>
            <hr />
            <input type='submit' value='Save Form' />
        </form>
        <?
        Functions::PrintFooter();
    }
?>
